package no.nordicsemi.android.nrfmesh.auth.ui.register;

import android.content.Intent;
import android.os.Bundle;
import android.view.*;
import android.widget.*;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.motion.widget.MotionLayout;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import no.nordicsemi.android.nrfmesh.MainScreenActivity;
import no.nordicsemi.android.nrfmesh.R;
import no.nordicsemi.android.nrfmesh.auth.data.AuthRepository;
import no.nordicsemi.android.nrfmesh.auth.session.SessionManager;
import no.nordicsemi.android.nrfmesh.auth.ui.AuthViewModel;
import no.nordicsemi.android.nrfmesh.widgets.CustomControlsActivity;

public class RegDoctorProfileFragment extends Fragment {
    private AuthViewModel vm;
    private EditText etName, etHospital;
    private ProgressBar pb;
    private TextView tvError;

    @Nullable @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_reg_doctor_profile, container, false);
        vm = new ViewModelProvider(requireActivity()).get(AuthViewModel.class);

        etName = v.findViewById(R.id.etName);
        etHospital = v.findViewById(R.id.etHospital);
        pb = v.findViewById(R.id.pb);
        tvError = v.findViewById(R.id.tvError);

        v.findViewById(R.id.btnFinish).setOnClickListener(view -> finishReg());
        return v;
    }

    private void finishReg() {
        tvError.setText(null);
        String name = etName.getText().toString().trim();
        String hospital = etHospital.getText().toString().trim();
        if (name.length() < 2) { tvError.setText("请输入姓名"); return; }
        if (hospital.length() < 2) { tvError.setText("请输入医院名称"); return; }

        pb.setVisibility(View.VISIBLE);
        new Thread(() -> {
            try {
                AuthRepository repo = new AuthRepository(requireContext());
                long uid = repo.registerDoctor(vm.id, vm.pd, name, hospital);
                new SessionManager(requireContext()).save(uid, AuthRepository.ROLE_DOCTOR, name);

                requireActivity().runOnUiThread(() -> {
                    pb.setVisibility(View.GONE);
                    try {
                        AuthViewModel avm = new ViewModelProvider(requireActivity()).get(AuthViewModel.class);
                        boolean remember = avm.rememberOnDevice != null && avm.rememberOnDevice;
                        boolean autoLogin = avm.autoLoginAfterReg != null && avm.autoLoginAfterReg;
                        String plainPwd = vm.pd != null ? String.valueOf(vm.pd) : null;
                        avm.onLoginSucceeded(vm.id, name, remember, autoLogin, plainPwd);
                    } catch (Throwable ignore) { }
                    // 添加延迟导航，确保网络和数据初始化完成
                    new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(() -> {
                        startActivity(new Intent(requireContext(), CustomControlsActivity.class));
                        requireActivity().finish();
                    }, 1000); // 延迟1秒
                });
            } catch (Exception ex) {
                requireActivity().runOnUiThread(() -> { pb.setVisibility(View.GONE); tvError.setText(ex.getMessage()); });
            }
        }).start();
    }
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 追加这一行
        applyHeroPaneEnhancements(view);
    }
    /** 右栏卡片入场动效 + 文案可选中（与登录页一致） */
    private void applyHeroPaneEnhancements(@NonNull View root) {
        MotionLayout ml = root.findViewById(R.id.heroPane);
        if (ml != null) {
            ml.post(ml::transitionToEnd);
        }
        int[] textIds = { R.id.tvDeviceIntro, R.id.tvBullets, R.id.tvDisclaimer };
        for (int id : textIds) {
            View v = root.findViewById(id);
            if (v instanceof TextView) {
                ((TextView) v).setTextIsSelectable(true);
            }
        }
    }
}
